from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    # 查询商品频道和分类
    categories_dict = OrderedDict()  # 创建一个有序的字典（先添加的key-value在前面）
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:  # 总共是11个频道，每个频道中 基本上有3、4个商品类别
        group_id = channel.group_id  # 当前频道的id
        if group_id not in categories_dict:
            categories_dict[group_id] = {'channels': [], 'sub_cats': []}
        category_1 = channel.category  # 当前频道的 商品类别（1级分类）
        # 追加1级分类信息到当前频道
        categories_dict[group_id]['channels'].append({
            'id': category_1.id,
            'name': category_1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别（2、3级分类）
        for category_2 in category_1.subs.all():
            # 将2级分类模型类对象中的信息，转换为字典
            category_2_dict = {"id": category_2.id, "name": category_2.name, "sub_cats": []}
            for category_3 in category_2.subs.all():
                # 将3级分类模型类对象中的信息，转换为字典
                category_3_dict = {"id": category_3.id, "name": category_3.name}
                category_2_dict["sub_cats"].append(category_3_dict)
            categories_dict[group_id]['sub_cats'].append(category_2_dict)
    return categories_dict

def get_breadcrumb(category):
    """
    获取面包屑导航
    :param category: 商品类别
    :return: 面包屑导航字典
    """
    breadcrumb = dict(
        category_1='',
        category_2='',
        category_3=''
    )
    if category.parent is None:
        # 当前类别为一级类别
        breadcrumb['category_1'] = category
    elif category.subs.count() == 0:
        # 当前类别为三级
        breadcrumb['category_3'] = category
        cat2 = category.parent
        breadcrumb['category_2'] = cat2
        breadcrumb['category_1'] = cat2.parent
    else:
        # 当前类别为二级
        breadcrumb['category_2'] = category
        breadcrumb['category_1'] = category.parent

    return breadcrumb